<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统权限管理</span>
          <div>
            <el-button type="success" @click="handleExpandAll">全部展开</el-button>
            <el-button type="info" @click="handleCollapseAll">全部收起</el-button>
            <el-button type="primary" :disabled="!multipleSelection.length" @click="batchEnable">批量启用</el-button>
            <el-button type="warning" :disabled="!multipleSelection.length" @click="batchDisable">批量禁用</el-button>
            <el-button type="danger" :disabled="!multipleSelection.length" @click="batchDelete">批量删除</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        ref="permissionTableRef"
        v-loading="loading"
        :data="permissionList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="权限名称" prop="name" min-width="200" />
        <el-table-column label="权限标识" prop="code" min-width="200" />
        <el-table-column label="权限类型" prop="type" width="120">
          <template #default="{ row }">
            <el-tag :type="getPermissionTypeTag(row.type)">
              {{ getPermissionTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="图标" prop="icon" width="100" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :size="20"><component :is="row.icon" /></el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="路由路径" prop="path" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="排序" prop="sort" width="80" align="center" />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="'active'"
              :inactive-value="'inactive'"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button 
              v-if="row.type !== 'operation'" 
              size="small" 
              type="success" 
              @click="handleAdd(row)">添加子项</el-button>
            <el-button size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
            <el-button 
              v-if="!['dashboard', 'system'].includes(row.code)" 
              size="small" 
              type="danger" 
              @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑权限对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogType === 'add' ? '添加权限' : '编辑权限'" 
      width="580px"
      @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="父级权限" v-if="dialogType === 'add'">
          <el-input v-model="parentName" disabled />
        </el-form-item>
        
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权限名称" />
        </el-form-item>
        
        <el-form-item label="权限标识" prop="code">
          <el-input 
            v-model="form.code" 
            placeholder="请输入权限标识，例如：system:user:list" 
            :disabled="dialogType === 'edit'" 
          />
          <div class="form-tip">权限标识一旦创建不可修改，将用于后端权限判断</div>
        </el-form-item>
        
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <template v-if="form.type === 'menu'">
          <el-form-item label="图标" prop="icon">
            <el-input v-model="form.icon" placeholder="请输入图标名称，例如：Menu" />
          </el-form-item>
          
          <el-form-item label="路由路径" prop="path">
            <el-input v-model="form.path" placeholder="请输入路由路径，例如：/system/user" />
          </el-form-item>
          
          <el-form-item label="组件路径" prop="component">
            <el-input v-model="form.component" placeholder="请输入组件路径，例如：system/user/index" />
          </el-form-item>
        </template>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
          <span class="form-tip">数字越小排序越靠前</span>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="'active'">启用</el-radio>
            <el-radio :value="'inactive'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="提示" width="360px">
      <div>确定要删除该权限及其所有子权限吗？此操作不可恢复！</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { permissionApi } from '@/api/permission'
import type { Permission } from '@/types'
import { usePermissionStore } from '@/store/modules/permission'
import { asyncRoutes } from '@/router'

const loading = ref(false)
const permissionList = ref<Permission[]>([])
const permissionTableRef = ref()
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const parentName = ref('')
const parentId = ref('')
const deleteDialogVisible = ref(false)
const deleteId = ref('')
const formRef = ref<FormInstance | null>(null)
const multipleSelection = ref<Permission[]>([])

const permissionStore = usePermissionStore()
permissionStore.setRoutes(asyncRoutes)

// 表单数据
const form = reactive<Partial<Permission & { description?: string }>>({
  name: '',
  code: '',
  type: 'menu',
  icon: '',
  path: '',
  component: '',
  sort: 1,
  status: 'active',
  description: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 30, message: '权限名称长度在2到30个字符之间', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限标识', trigger: 'blur' },
    { min: 2, max: 50, message: '权限标识长度在2到50个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '请输入组件路径', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 权限类型选项
const typeOptions = [
  { value: 'menu', label: '菜单' },
  { value: 'operation', label: '操作' },
  { value: 'data', label: '数据' }
]

// 获取权限类型名称
const getPermissionTypeName = (type: string) => {
  const map: Record<string, string> = {
    menu: '菜单',
    operation: '操作',
    data: '数据'
  }
  return map[type] || '未知'
}

// 获取权限类型标签样式
const getPermissionTypeTag = (type: string) => {
  const map: Record<string, string> = {
    menu: 'success',
    operation: 'warning',
    data: 'primary'
  }
  return map[type] || 'info'
}

// 查询权限列表
const getList = async () => {
  loading.value = true
  try {
    const res = await permissionApi.getList()
    permissionList.value = res.list
  } catch (e) {
    ElMessage.error('获取权限失败')
  } finally {
    loading.value = false
  }
}

// 切换状态
const handleStatusChange = async (row: Permission) => {
  const statusText = row.status === 'active' ? '启用' : '禁用'
  
  try {
    // 这里可以调用实际的API
    // await permissionApi.updateStatus(row.id, row.status)
    ElMessage.success(`${statusText}成功`)
  } catch (error) {
    console.error(`${statusText}权限失败:`, error)
    ElMessage.error(`${statusText}失败`)
    // 恢复状态
    row.status = row.status === 'active' ? 'inactive' : 'active'
  }
}

// 全部展开
const handleExpandAll = () => {
  if (!permissionTableRef.value) return
  // 获取所有权限ID作为展开的行
  const expandKeys = getAllIds(permissionList.value)
  // 设置展开的行
  permissionTableRef.value.setExpandRowKeys?.(expandKeys)
}

// 全部收起
const handleCollapseAll = () => {
  if (!permissionTableRef.value) return
  // 清空展开的行
  permissionTableRef.value.setExpandRowKeys?.([])
}

// 获取所有ID
const getAllIds = (data: Permission[]): string[] => {
  let ids: string[] = []
  data.forEach(item => {
    ids.push(item.id)
    if (item.children && item.children.length > 0) {
      ids = ids.concat(getAllIds(item.children))
    }
  })
  return ids
}

// 添加权限
const handleAdd = (row: Permission) => {
  dialogType.value = 'add'
  dialogVisible.value = true
  parentName.value = row.name
  parentId.value = row.id
  
  // 根据父级权限类型设置默认子权限类型
  if (row.type === 'menu') {
    form.type = 'operation'
  } else {
    form.type = 'menu'
  }
}

// 编辑权限
const handleUpdate = (row: Permission) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  
  // 复制数据到表单，不再使用description属性
  Object.assign(form, {
    ...row
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    name: '',
    code: '',
    type: 'menu',
    icon: '',
    path: '',
    component: '',
    sort: 1,
    status: 'active',
    description: ''
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 添加
          // await permissionApi.create({
          //   ...form,
          //   parentId: parentId.value
          // })
          ElMessage.success('添加成功')
        } else {
          // 编辑
          // await permissionApi.update(form.id as string, form)
          ElMessage.success('更新成功')
        }
        
        // 关闭对话框
        dialogVisible.value = false
        
        // 刷新数据
        getList()
      } catch (error) {
        console.error('保存权限失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 删除权限
const handleDelete = async (row: Permission) => {
  try {
    await ElMessageBox.confirm('确定要删除该权限及其所有子权限吗？', '提示', { type: 'warning' })
    await permissionApi.delete({ id: row.id })
    ElMessage.success('删除成功')
    getList()
  } catch {}
}

const handleSelectionChange = (val: Permission[]) => {
  multipleSelection.value = val
}

const batchEnable = async () => {
  if (!multipleSelection.value.length) return
  await permissionApi.batchUpdateStatus(multipleSelection.value.map(i => i.id), 'active')
  ElMessage.success('批量启用成功')
  getList()
}

const batchDisable = async () => {
  if (!multipleSelection.value.length) return
  await permissionApi.batchUpdateStatus(multipleSelection.value.map(i => i.id), 'inactive')
  ElMessage.success('批量禁用成功')
  getList()
}

const batchDelete = async () => {
  if (!multipleSelection.value.length) return
  await ElMessageBox.confirm('确定要批量删除选中的权限及其所有子权限吗？', '提示', { type: 'warning' })
  await permissionApi.batchDelete(multipleSelection.value.map(i => i.id))
  ElMessage.success('批量删除成功')
  getList()
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  span {
    font-size: 18px;
    font-weight: bold;
  }
}

.form-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 13px;
}
</style> 